﻿using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;

namespace QuickTuner.Util
{
    // TODO: Test this.

    public static partial class FrameworkExtensions
    {
        // serialize object to stream in binary form
        public static void BinarySerialize<T>(this T obj, Stream s)
        {
            var bf = new BinaryFormatter();
            bf.Serialize(s, obj);
        }

        // serialize object to stream in xml form
        public static void XmlSerialize<T>(this T obj, Stream s)
        {
            var xs = new XmlSerializer(typeof(T));
            xs.Serialize(s, obj);
        }

        /// <summary>
        /// Deserializes the supplied type from the Stream. Automatically
        /// switch between binary and xml formats by detecting the first byte of
        /// the stream.
        /// </summary>
        public static T DeserializeBinaryOrXml<T>(this Stream s)
        {
            // read the first byte to determine the format of serialization
            var b = s.ReadByte();
            s.Seek(0, SeekOrigin.Begin);

            T instance;

            // if first byte is a bracket, then it's probably Xml
            // else it's probably binary-formatted
            if (b == '<') {
                var xs = new XmlSerializer(typeof(T));
                instance =  (T)xs.Deserialize(s);

            } else {
                var bf = new BinaryFormatter();
                instance = (T)bf.Deserialize(s);

            }

            return instance;
        }
    }
}